<?php

namespace App\Http\Middleware;

use App\Http\Services\AdminManager;
use App\Http\Services\MerchantManager;
use App\Http\Services\UserManager;
use App\Staff;
use App\User;
use Closure;
use App\Role;
use Illuminate\Support\Facades\DB;

class Permission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$permissions)
    {
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        if(!empty($adminUser->staff_key)){
            $staff = Staff::whereStaffKey($adminUser->staff_key)->first();
            if($staff){
                return $next($request);
            }
        }


        if(!$adminUser->hasRole('system_admin')){
            if (!$adminUser->can(explode('|', $permissions)))
                return response()->json(["level"=>"error","message"=>"无权限访问","data"=>"no_permission"]);
        }

//        if(!$MerchantUser->hasRole('system_admin') && !$MerchantUser->hasRole('merchant_admin')){
//            if (!$MerchantUser->can(explode('|', $permissions)))
//                return response()->json(["level"=>"error","message"=>"无权限访问","data"=>"no_permission"]);
//        }

        return $next($request);
    }
}
